import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Menu,
  Modal,
  message,
  Divider,
  Popconfirm,
  Upload,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import UploadFileForm from './sub/UploadFileForm';
import {ruleP,nameMaxLength,remarkMaxLength} from '@/utils/rule'
import styles from '../search.less';
const { TextArea } = Input;
const FormItem = Form.Item;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const CreateForm = Form.create()(props => {
  const { modalVisible, form, addDataFn, updateFn, handleModalVisible, text, } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();

      if(text) {
        updateFn(fieldsValue,text)
      }else{
        addDataFn(fieldsValue);
      }
    });
  };
  return (
    <Modal
      destroyOnClose
      width={640}
      title={text?'编辑弱密码':'新增弱密码'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="弱密码">
        {form.getFieldDecorator('weakPsw', {
          rules: [{ required: true,whitespace:true, message: '弱密码不能为空'},{pattern:new RegExp(ruleP(1)[0],'g'), message:ruleP(1)[1]},{max:nameMaxLength()[0], message:nameMaxLength()[1]}],initialValue: text&&text.dataDictValue || ''
        })(<Input placeholder="请输入" />)}
      </FormItem>

      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="备注">
        {form.getFieldDecorator('note',{rules:[{max:remarkMaxLength()[0], message:remarkMaxLength()[1]}],initialValue: text&&text.remark || ''})(<TextArea
          style={{ minHeight: 32 }}
          rows={2}
        />)}
      </FormItem>
    </Modal>
  );
});


/* eslint react/no-multi-comp:0 */
@connect(({ weakPsw, loading }) => ({
  weakPsw,
  loading: loading.models.weakPsw,
}))


@Form.create()
class weakPswList extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    formValues: {},
    selectedRows: [],
    stepFormValues: {},
    text: {},
    uploadVisible: false, //导入窗口
  };

  columns = [
    {
      title: '序号',
      render: (text, record, index) => (
        index+1
      ),
    },
    {
      title: '弱密码',
      dataIndex: 'dataDictValue',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width:'50%',
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true,text)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => this.deleteData(text.id)}>删除</a>
        </Fragment>
      ),
    },
  ];

  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };

  batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };


  // 删除方法
  handleDeleteData(id) {
    const { dispatch } = this.props;
    const values = {
      id
    };

    dispatch({
      type: 'weakPsw/remove',
      payload: values,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
          this.setState({selectedRows: []})
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }


    // 分页查询列表
  pageList(data,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      dataDictValue: data && data.weakPsw || '', //弱密码
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    };
    dispatch({
      type: 'weakPsw/queryList',
      payload: values,
    });
  }

  componentDidMount() {
    this.pageList();
  }



  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        formValues: fieldsValue,
      })
      //点击查询  
      this.pageList(fieldsValue);
    });
  };

  // 新增弹框的显示和隐藏
  handleModalVisible = (flag,text) => {
    this.setState({
      modalVisible: !!flag,
      text: text
    });
  };

   // 新增导入的显示和隐藏
  handleUploadVisible = (flag) => {
    this.setState({
      uploadVisible: !!flag,
    });
  };

  // 更新接口
  updateFn = (fields,text) => {
    const { dispatch } = this.props;
    const params = {
      id: text.id,
      dataDictValue:fields.weakPsw,
      remark:fields.note,
    }
    dispatch({
      type: 'weakPsw/update',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
           Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const { dispatch } = this.props;
    const params = {
        dataDictValue:fields.weakPsw,//弱密码
        remark:fields.note,//备注
        status:0, //0正常1禁用
    }
    dispatch({
      type: 'weakPsw/add',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="弱密码">
              {getFieldDecorator('weakPsw')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderSimpleForm() : this.renderSimpleForm();
  }

  handleStandardTableChange(pagination, filters, sorter) {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues,pagination.pageSize,pagination.current-1);
  }

  render() {
    const {
      weakPsw: { data },
      loading,
    } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, stepFormValues, text, uploadVisible } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
      </Menu>
    );
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn
    };

    const uploadMethods = {
      handleUploadVisible: this.handleUploadVisible,
      pageList: this.pageList.bind(this),
    };

    return (
      <PageHeaderWrapper title="弱密码管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新增
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
              )}
            </div>
            <TableList
              className={styles.tdPadding}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange.bind(this)}
              rowKey={record => record.id}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} text={text}/>
        {uploadVisible?(
          <UploadFileForm {...uploadMethods} uploadVisible={uploadVisible} isUser={false}/>
        ):null}
      </PageHeaderWrapper>
    );
  }
}

export default weakPswList;
